#!-*- encoding:utf8 -*-

# Create your views here.

from django.template import Template, Context, RequestContext
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import user_passes_test, login_required
from django.contrib.auth.models import User
from osmp.flow import models
from osmp.flow.models import Flow, FlowAction

from django.db.models import Q

from osmp.flow.forms import*
from osmp.host.models import *
from osmp.users.models import UserProfile
from osmp import settings
from osmp.util import commom
import datetime
import json

#def test(request):
#     return HttpResponse("hello, world")


@login_required
def tasklist(request):
    todoList = []
    tasks = Flow.objects.order_by('-id').all()
    for t in tasks:
        t.oprate = settings.OP_CHOICES[str(t.status)]
        if t.auth_uid == request.user.username and t.oprate == u'等待审核':
            todoList.append(t)
        if t.op_uid == request.user.username and t.oprate == u'等待操作':
            todoList.append(t)
        if t.send_uid == request.user.username and t.oprate == u'等待确认':
            todoList.append(t)
        if t.send_uid == request.user.username and t.oprate == u'修改':
            todoList.append(t)
        
    user = UserProfile.objects.all()
    plist = Product.objects.all()
    request.session['User'] = user
    request.session['plist'] = plist
    return render_to_response("flow.html",locals())

@login_required
def search(request):
    messages = []
    q = Q()
    #与我相关
    if 'a' in request.GET:
        name = request.user.username
        uid = request.user.id
        print uid
        q &= Q(auth_uid = uid)|Q(op_uid = uid)
        myList = Flow.objects.filter(q).order_by('-id')
        for t in myList:
            t.status = settings.OP_CHOICES[str(t.status)]
        user = request.session.get('User')
        plist = request.session.get('plist')
        return render_to_response("allflowlist.html",locals())
    
    #q &= Q(fid = id)
    fname = request.POST.get('fname', '')
    if fname:
        q &= Q(tname__contains = fname)
    pid = request.POST.get('pid', '')
    if pid:
        q &= Q(pid = pid)
    uid = request.POST.get('uid', '')
    if uid:
        q &= Q(auth_uid = uid)|Q(op_uid = uid)
    myList = Flow.objects.filter(q).order_by('-id')
    if not myList:
        messages.append("null")
    if (fname or pid or uid) and myList:
        flag = "open"
        request.session['myList'] = myList
    for t in myList:
        t.status = settings.OP_CHOICES[str(t.status)]
    print ("fname:%s,pid:%s,uid:%s")%(fname,pid,uid)
    user = request.session.get('User')
    plist = request.session.get('plist')
    return render_to_response("allflowlist.html",locals())

@login_required
def searcht(request):
    messages = []
    errors = []
    if request.GET.get('action') == "csv":
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        start = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d %H:%M:%S') #str(long((time.time()*1000 - (7 * 24 * 60 * 60))))
        end = now
        flag = "open"
    if request.method == 'POST':
        if not request.POST.get('start', ''):
            errors.append('请输入开始时间')
        if not request.POST.get('end', ''):
            errors.append('请输入截止时间')
        if request.POST.get('start', '') > request.POST.get('end', ''):
            errors.append('时间输入异常')
        if errors:
            return render_to_response("allflowlist.html",locals())
        else:
            start = "%s 00:00:00"%request.POST.get('start')
            end = "%s 23:59:59"%request.POST.get('end')
            flag = "open"
            print start
            print end
    user = request.session.get('User')
    plist = request.session.get('plist')
    myList = Flow.objects.filter(timestamp__range=(start,end))
    for t in myList:
        t.status = settings.OP_CHOICES[str(t.status)]
    request.session['myList'] = myList
    return render_to_response("allflowlist.html",locals())

@login_required
def mylist(request):
    myList = Flow.objects.filter(send_uid = request.user).order_by('-id').all()
    for t in myList:
        t.status = settings.OP_CHOICES[str(t.status)]
    return render_to_response("myflowlist.html",locals())

@login_required
def alllist(request):
    myList = Flow.objects.order_by('-id').all()
    for t in myList:
        t.status = settings.OP_CHOICES[str(t.status)]
    user = request.session.get('User')
    plist = request.session.get('plist')
    return render_to_response("allflowlist.html",locals())

@login_required
def filterlist(request):
    keyword = request.POST.get("keyword")
    op = request.POST.get("op")
    date = request.POST.get("date")
    print"%s,%s,%s"%(keyword,op,date)
    HttpResponse( keyword )


@login_required
def addtask(request):
    if request.method == 'POST':
        form = FlowForm(request.POST,  request.FILES)
        if form.is_valid():
            cd = form.cleaned_data
            #创建操作单记录
            f = Flow.objects.create(tname = cd['tname'],
                                pid = Product.objects.get(id = int(cd['pid'])),
                                hid = cd['hid'],
                                detail = cd['detail'],
                                send_uid = request.user.username,
                                auth_uid = cd['auth_uid'],
                                op_uid = cd['op_uid'],
                                attach = cd['attach'],
                                status = '1'
                    )
            #创建操作记录
            FlowAction.objects.create(  fid = f,
                                        uid =  request.user,
                                        event = "发起操作单",
                                        detail = cd['tname'],
                                        timestamp = datetime.datetime.now() 
                    )

            #邮件通知
            try:
                auth_uid = request.POST.get('auth_uid'),
                if auth_uid:
                    content = "有流程任务需要您核审。详情请访问OSMP系统。FLOW: %s" % cd['tname'].encode('utf-8')
                    commom.sendmail(UserProfile.objects.get(user__username = auth_uid[0]).mail, "OSMP: Flow Task",content)
                    content = "发起流程成功。详情请访问OSMP系统。FLOW: %s" % cd['tname'].encode('utf-8') 
                    commom.sendmail(request.session['User'].mail,"OSMP: Flow Task",content)
            except:
                pass
            return HttpResponseRedirect('/flow/mylist/')
    else:
        form = FlowForm()
    return render_to_response( "addtask.html", locals())


@login_required
def flow_view(request, id):
    task = Flow.objects.get(id = int(id))
    task.status = settings.OP_CHOICES[str(task.status)]
    
    actions = FlowAction.objects.filter(fid = task)

    return render_to_response( "flowview.html", locals())
    #return render_to_response( "flowaction.html", locals())

@login_required
def flow_auth(request, id):
    if request.method == 'POST':
        id = request.POST.get("tid")
        task = Flow.objects.get(id = int(id))
        if task.auth_uid == request.user.username:
            task.status = '2'
            task.save()
            #创建操作记录
            FlowAction.objects.create(  fid = task,
                                        uid =  request.user,
                                        event = u"审核操作单",
                                        detail = u"审核通过:" + request.POST.get('tname'),
                                        timestamp = datetime.datetime.now() 
                    )


            message = u"审核通过，可以进行下一步操作!"

            #邮件通知
            content = "任务审核通过。详情请访问OSMP系统。FLOW: %s" % task.tname.encode('utf-8') 
            commom.sendmail(UserProfile.objects.get(user__username = task.send_uid).mail, "OSMP: Flow Task",content)
            HttpResponseRedirect("/flow/%s/1" % id)
        else:
            errors = u"审核没有通过，您没有审核权限!"
            HttpResponseRedirect("/flow/%s/1" % id)
    
    else:
        task = Flow.objects.get(id = int(id))
        actions = FlowAction.objects.filter(fid = task)
    return render_to_response( "flowauth.html", locals())

@login_required
def flow_op(request, id):
    if request.method == 'POST':
        id = request.POST.get("tid")
        task = Flow.objects.get(id = int(id))
        if task.op_uid == request.user.username:
            task.status = '3'
            task.save()
            #创建操作记录
            FlowAction.objects.create(  fid = task,
                                        uid =  request.user,
                                        event = u"执行操作单",
                                        detail = u"执行完成:" + request.POST.get('tname'),
                                        timestamp = datetime.datetime.now() 
                    )

            message = u"操作成功，请回复CHECKLIST!"

            #邮件通知
            content = "任务操作成功。详情请访问OSMP系统。FLOW: %s" % task.tname.encode('utf-8')
            commom.sendmail(UserProfile.objects.get(user__username = task.send_uid).mail, "OSMP: Flow Task",content)
            HttpResponseRedirect("/flow/%s/0" % id)
        else:
            errors = u"对不起，您没有操作权限!"
            HttpResponseRedirect("/flow/%s/2" % id)
    
    else:
        task = Flow.objects.get(id = int(id))
        actions = FlowAction.objects.filter(fid = task)
    return render_to_response( "flowop.html", locals())



@login_required
def flow_commit(request, id):
    if request.method == 'POST':
        id = request.POST.get("tid")
        task = Flow.objects.get(id = int(id))
        if task.send_uid == request.user.username:
            task.status = '5'
            task.save()
            #创建操作记录
            FlowAction.objects.create(  fid = task,
                                        uid =  request.user,
                                        event = u"确认操作单",
                                        detail = u"确认完成:" + request.POST.get('tname'),
                                        timestamp = datetime.datetime.now() 
                                        )
            message = u"恭喜你，整个任务已经完成!"
            
            #邮件通知
            content = "任务完成。详情请访问OSMP系统。FLOW: %s" % task.tname.encode('utf-8')
            commom.sendmail(UserProfile.objects.get(user__username = task.send_uid).mail, "OSMP: Flow Task",content)
            HttpResponseRedirect("/flow/%s/0" % id)
        else:
            errors = u"对不起，您没有确认权限!"
            HttpResponseRedirect("/flow/%s/2" % id)
    
    else:
        task = Flow.objects.get(id = int(id))
        actions = FlowAction.objects.filter(fid = task)
    return render_to_response( "flowcommit.html", locals())


@login_required
def set_modify(request, id):
    res = {'flag': 'true'}
    try:
        task = Flow.objects.get(id = int(id))
        if task.auth_uid == request.user.username or  task.op_uid == request.user.username :
            task.status = '4'
            task.save()
             #创建操作记录
            FlowAction.objects.create(  fid = task,
                                        uid =  request.user,
                                        event = u"打回操作单",
                                        detail = u"打回修改:" + task.tname,
                                        timestamp = datetime.datetime.now() 
                                        )

            HttpResponseRedirect("/flow/%s/0" % id)

    except:
        res = {'flag': 'false'}
    return HttpResponse(json.dumps(res))


@login_required
def flow_modify(request, id):
    if request.method == 'POST':
        form = FlowForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            task = Flow.objects.get(id = id)

            if task.send_uid != request.user.username:
                return Http404
            task.tname = cd['tname']
            task.pid = Product.objects.get(id = cd['pid'])
            task.detail = cd['detail']
            task.auth_uid = cd['auth_uid']
            task.op_uid = cd['op_uid']
            if cd['attach']:
                task.attach = cd['attach']
            task.status = 1
            task.save()

            #创建操作记录
            FlowAction.objects.create(  fid = task,
                                       uid =  request.user,
                                       event = "修改操作单",
                                        detail = cd['tname'],
                                        timestamp = datetime.datetime.now()                     )
            return HttpResponseRedirect('/flow/mylist/')
    else:
        task = Flow.objects.get(id = int(id))
    return render_to_response( "flowmodify.html", locals())


@login_required
def ajax_goback(request):
    if request.method == 'POST':
        try:
            id = int(request.POST.get('id'))
            data = request.POST.get('data')
            task = Flow.objects.get(id = id)

            task.status = 4
            task.save()
            FlowAction.objects.create(  fid = task,
                                       uid =  request.user,
                                       event = "打回操作单",
                                        detail = data,
                                        timestamp = datetime.datetime.now()                     )

            content = "任务被打回。详情请访问OSMP系统。FLOW: %s. 打回理由：%s" % (task.tname.encode('utf-8'), data.encode('utf-8'))
            commom.sendmail(UserProfile.objects.get(user__username = task.send_uid).mail, "OSMP: Flow Task",content)
            return HttpResponse('true')
        except:
            raise
            return HttpResponse('false')
    
    
@login_required
def ajax_opreplay(request):
    if request.method == 'POST':
        try:
            id = int(request.POST.get('id'))
            data = request.POST.get('data')
            task = Flow.objects.get(id = id)

            FlowAction.objects.create(  fid = task,
                                       uid =  request.user,
                                       event = "操作完成",
                                        detail = data,
                                        timestamp = datetime.datetime.now()                     )

            content = "操作完成。详情请访问OSMP系统。FLOW: %s. CHECKLIST：%s" % (task.tname.encode('utf-8'), data.encode('utf-8'))
            commom.sendmail(UserProfile.objects.get(user__username = task.send_uid).mail, "OSMP: Flow Task",content)
            return HttpResponse('true')
        except:
            return HttpResponse('false')
    


@login_required
def ajax_taskfail(request):
    if request.method == 'POST':
        try:
            id = int(request.POST.get('id'))
            task = Flow.objects.get(id = id)
            task.status = 6
            task.save()

            FlowAction.objects.create(  fid = task,
                                       uid =  request.user,
                                       event = "任务失败",
                                        detail = task.tname,
                                        timestamp = datetime.datetime.now()                     )

            content = "任务失败。详情请访问OSMP系统。FLOW: %s" % (task.tname.encode('utf-8'))
            commom.sendmail(UserProfile.objects.get(user__username = task.send_uid).mail, "OSMP: Flow Task",content)
            return HttpResponse('true')
        except:
            return HttpResponse('false')

#CSV的导出
import time,csv
def export(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(mimetype='text/csv')
    response.write('\xEF\xBB\xBF')
    tim = str(long(time.time()*1000))
    s = 'attachment; filename=Flow-%s.csv'%tim
    response['Content-Disposition'] = s
    myList = request.session.get('myList')
    print myList
    writer = csv.writer(response)
    
    writer.writerow([u'上线单名称'.encode('gbk'), u'对应模块名称'.encode('gbk'), u'对应主机名称'.encode('gbk'), u'审核员'.encode('gbk'), u'操作员'.encode('gbk'), u'操作'.encode('gbk')])
    for l in myList:
        tname = l.tname.encode('gbk')
        pid = l.pid.name.encode('gbk')
        print pid
        hid = l.hid.encode('gbk')
        auth = l.auth_uid.encode('gbk')
        op = l.op_uid.encode('gbk')
        status = l.status.encode('gbk')
        writer.writerow([tname,pid,hid,auth,op,status])
    
    user = request.user.username
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    writer.writerow([u"用户：".encode('gbk'),user,u"操作时间：".encode('gbk'),now])
    return response
